package cn.cumulomq.service;

import java.util.Date;
import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.filter.codec.ProtocolEncoderException;

import cn.ait.umc.endpoint.Endpoint;
import cn.ait.umc.exception.ConnectException;
import cn.ait.umc.exception.ContainInvalidCharactersException;
import cn.ait.umc.exception.SendFailedException;
import cn.ait.umc.message.AFTNMessage;
import cn.ait.umc.mina.MessageParser;
import cn.cumulomq.MQXMain;
import cn.cumulomq.entity.AMHSMessage;
import cn.cumulomq.entity.TeleMessage;
import cn.cumulomq.parse.ParseManage;
import cn.cumulomq.utils.MessageUtil;

/**
 * 上层业务发送报文服务,根据发电地址选择发送的线路,发送->解析->入库->通知,
 * @author maxuedong
 *
 */
public class SendMessageService {
	
	public static TeleMessage sendMessage(AFTNMessage message) throws ConnectException, ContainInvalidCharactersException, ProtocolEncoderException, SendFailedException{
		Endpoint endpoint = MQXMain.getInstance().addrEndpointMap.get(message.getOriginator().getAddress());
		TeleMessage tm=null;
		if(endpoint!=null){
			List<AFTNMessage> msgs;
			try {
				msgs = MessageUtil.splitAftn(message);
			} catch (Exception e) {
				throw new SendFailedException("Split message error.");
			}
			for(AFTNMessage am:msgs){
				am.setCid(endpoint.getOutCid());
				am.setCsn(endpoint.getNextOutCsn());
				am.setSentDate(new Date());
				try {
					MessageParser.encode5(IoBuffer.allocate(1024).setAutoExpand(true),
					        am, endpoint.getLc().getConfig().getAftnProtocolParam(), 0, false);
				} catch (Exception e) {
					throw new ProtocolEncoderException("Message encode5 failed.",e);
				}
				endpoint.doSend(am);
				tm = MessageUtil.createTeleFromUmc(am);
				TeleMessageService tms = new TeleMessageService(tm.getOriginator());
				ParseManage.getInstance().messageToJson(tm);
				tms.save(tm);
			}
		}else{
			throw new ConnectException();
		}
		return tm;
		
	}
	
	/**
	 * 发送AFTN&SITA电报
	 * @param message
	 * @throws ConnectException 
	 * @throws SendFailedException 
	 * @throws ProtocolEncoderException 
	 * @throws ContainInvalidCharactersException 
	 */
	public static void sendMessage(TeleMessage message) throws ContainInvalidCharactersException, ProtocolEncoderException, SendFailedException, ConnectException{
		Endpoint endpoint = MQXMain.getInstance().addrEndpointMap.get(message.getOriginator());
		if(endpoint!=null){
			endpoint.doSend(message);
			TeleMessageService tms = new TeleMessageService(message.getOriginator());
			ParseManage.getInstance().messageToJson(message);
			tms.save(message);
		}else{
			throw new ConnectException();
		}
	}
	public static void sendMessage(AMHSMessage message){
		
	}
}
